﻿using UnityEngine;
using System.Collections;
using PBMessage;

public class GSPackageHandler
{
    GameScene mGameScene;
    public void Start(GameScene gameScene)
    {
        mGameScene = gameScene;
        Game.Inst.Net.SetHandler(PBMesasgeID.SC_MoveUnit, OnSCMoveUnit);
        Game.Inst.Net.SetHandler(PBMesasgeID.SC_GameSceneTick, OnSCGameSceneTick);
        Game.Inst.Net.SetHandler(PBMesasgeID.SC_UnitAddMover, OnSCUnitAddMover);
        Game.Inst.Net.SetHandler(PBMesasgeID.SC_OptUnit,OnSCOptUnit);
    }

    void OnSCMoveUnit(PBPackage data)
    {
        SC_MoveUnit moveUnit = data.Data as SC_MoveUnit;
        mGameScene.GetUnit(moveUnit.UnitId).MoverController.OnServerMover(moveUnit);
    }
    void OnSCGameSceneTick(PBPackage data)
    {
        SC_GameSceneTick tick = data.Data as SC_GameSceneTick;
        if (mGameScene.ServerTime == 0)
        {
            mGameScene.ServerTime = tick.Time;
            mGameScene.PreServerTime = tick.Time;
        }
        else
        {
            mGameScene.PreServerTime = mGameScene.ServerTime;
            mGameScene.ServerTime = tick.Time;
        }
        mGameScene.ServerDT = (mGameScene.ServerTime - mGameScene.PreServerTime);


        mGameScene.ServerUpdate(mGameScene.ServerDT);
    }

    void OnSCUnitAddMover(PBPackage data)
    {
        SC_UnitAddMover addMover = data.Data as SC_UnitAddMover;
        Mover newMover = MoverManager.Instance.CreateMover(addMover);
        Unit curUnit = mGameScene.GetUnit(addMover.UnitId);
        curUnit.AddMover(newMover);
        newMover.Start(curUnit);
    }

    void OnSCOptUnit(PBPackage data)
    {
        SC_OptUnit optUnit = data.Data as SC_OptUnit;
        Unit unit = mGameScene.GetUnit(optUnit.UnitId);
        mGameScene.RemoveUnit(unit.GUID);
        GameObject.Destroy(unit.gameObject);
    }

}
